//--------------------------------------------------------------------------
// 
//  Copyright (c) Chili Software.  All rights reserved. 
// 
//  File: PerThreadObjectContextFactoryPolicy.cs
//
//  Description: Creates a new ObjectContext instance per thread.
// 
//--------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace Chili.Opf3
{
	/// <summary>
	/// This class creates a new <see cref="ObjectContext">ObjectContext</see> instance
	/// for each thread that is calling <see cref="ObjectContextFactory">ObjectContextFactory</see>'s
	/// GetContext method.
	/// </summary>
	public class PerThreadObjectContextFactoryPolicy : ObjectContextFactoryPolicyBase
	{
		[ThreadStatic]
		private static ObjectContext _context;

		/// <summary>
		/// Creates a new instance of the <see cref="PerThreadObjectContextFactoryPolicy">PerThreadObjectContextFactoryPolicy Class</see>.
		/// </summary>
		/// <param name="creator">The delegate that creates new <see cref="ObjectContext">ObjectContext</see> instances.</param>
		public PerThreadObjectContextFactoryPolicy(ObjectContextFactoryCreatorDelegate creator)
			: base(creator)
		{
		}

		/// <summary>
		/// Returns whether a new <see cref="ObjectContext">ObjectContext</see> instance is required.
		/// </summary>
		/// <returns>True if a new instance is required; false otherwise.</returns>
		protected override bool IsNewObjectContextRequired()
		{
			return (_context == null);
		}

		/// <summary>
		/// Stores the new <see cref="ObjectContext">ObjectContext</see> instance.
		/// </summary>
		/// <param name="context">The <see cref="ObjectContext">ObjectContext</see> to store.</param>
		/// <returns>The <see cref="ObjectContext">ObjectContext</see> instance that has been stored.</returns>
		protected override ObjectContext StoreNewObjectContext(ObjectContext context)
		{
			// Store the context.
			_context = context;
			// Return it.
			return context;
		}

		/// <summary>
		/// Gets an existing <see cref="ObjectContext">ObjectContext</see> instance.
		/// </summary>
		/// <returns>An <see cref="ObjectContext">ObjectContext</see> instance.</returns>
		protected override ObjectContext GetExistingObjectContext()
		{
			return _context;
		}
	}
}
